package com.framework.bdf4j.msg.sender;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.framework.bdf4j.comm.exception.ExceptionUtil;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.msg.constant.PublicConstant;
import com.framework.bdf4j.msg.entity.MessageResultResolver;
import com.framework.bdf4j.msg.entity.dto.SysMessagesSaveDTO;
import com.framework.bdf4j.msg.entity.vo.SysMsgResultVO;
import com.framework.bdf4j.msg.entity.vo.SysUserVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 站内消息发送器
 *
 * @author shan.deng
 * @date 2020-07-15 16:06:43
 */
@Component("websocketMessageSender")
@Slf4j
public class WebSocketMessageSender extends Sender {

    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;


    /**
     * 发送站内消息
     * @param sysMessagesSaveDTO
     */
    @Override
    @Async
    public void send(Integer msgId, SysMessagesSaveDTO sysMessagesSaveDTO, List<SysUserVO> users) throws RuntimeException {

        MessageResultResolver messageResultResolver = new MessageResultResolver();

        messageResultResolver.setMsgId(msgId);

        messageResultResolver.setContent(sysMessagesSaveDTO.getMsgContent());

        messageResultResolver.setTitle(sysMessagesSaveDTO.getMsgTitle());

        List<SysMsgResultVO> results = new ArrayList<>();

        users.stream().forEach(sysUser -> {
            SysMsgResultVO sysMsgResultVO = sendOneByOne(sysUser, messageResultResolver);
            results.add(sysMsgResultVO);
        });
        recordResult(msgId,results);
    }

    private SysMsgResultVO sendOneByOne(SysUserVO sysUser, MessageResultResolver messageResultResolver) {
        try {
            simpMessagingTemplate.convertAndSendToUser(sysUser.getLoginname(),"/result", JSON.toJSONString(R.ok(messageResultResolver)));
            return new SysMsgResultVO(sysUser.getUserId(), PublicConstant.MSG_SEND_RESULT_SUCCESS_CODE, PublicConstant.MSG_SEND_RESULT_SUCCESS_TEXT,PublicConstant.SEND_TYPE_NET);
        }catch (Exception ex) {
            log.error("站内信息发送失败",ex);
            String reason = ExceptionUtil.getExceptionMessage(ex);
            return new SysMsgResultVO(sysUser.getUserId(), PublicConstant.MSG_SEND_RESULT_FAILURE_CODE,reason,PublicConstant.SEND_TYPE_NET);
        }
    }
}
